import { findAllClass1, findCatalogByClass1, selectLevel3 } from '../../service/api'

export default {
  namespaced: true,
  state: {
    lv1: [],
    expired: false,
    lv2: {},
    expiredLv2: {},
    lv4IDs: [],
    lv4: {}
  },
  mutations: {
    /* 保存数据 */
    saveLv1(state, payload) {
      state.lv1 = [...payload.result]
      state.expired = false
    },
    /* 过期数据 */
    setExpired(state) {
      state.expired = true
    },
    saveLv2(state, payload) {
      const { key, result } = payload
      state.lv2 = {
        ...state.lv2,
        [key]: result
      }
      delete state.expiredLv2[key]
    },
    setLv2Expired (state, { c1 }) {
      state.expiredLv2 = { ...state.expiredLv2, [c1]: true }
    },
    saveLv4 (state, { result }) {
      const lv4 = {}
      state.lv4IDs = result.map(v => {
        lv4[v.goodsid] = v
        return v.goodsid
      })
      state.lv4 = lv4
    }
  },
  actions: {
    /* 拉取数据 */
    async fetchLv1({ state, commit }) {
      const { lv1, expired } = state
      // lv1有数据且数据没有过期，则不需要fetch server
      if (lv1.length && !expired) return true
      const { data } = await findAllClass1()
      if (!data || +data.code !== 200) {
        return false
      }
      commit({
        type: 'saveLv1',
        result: data.result
      })
    },
    /**
     * 拉取lv2数据
     * @param { String } c1
     */
    async fetchLv2({ state, commit }, { c1 }) {
      const { lv2, expiredLv2 } = state
      /* 如果有数据且没有过期，则不需要从fetch server */
      if (lv2[c1] && lv2[c1].length && !expiredLv2[c1]) return true
      const { data } = await findCatalogByClass1({ id: c1 })
      if (!data || +data.code !== 200) return false
      commit({
        type: 'saveLv2',
        result: data.result,
        key: c1
      })
    },
    async fetchLv4 ({ state, commit }, { c2 }) {
      const { data } = await selectLevel3(c2)
      if (!data || +data.code !== 200) return false
      commit({
        type: 'saveLv4',
        result: data.result
      })
    }
  }
}
